package com.mwx.baselib.net;


import com.mwx.baselib.net.singer.SingerService;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/*
 * @author Bryan
 * @emil phantom3792@gmail.com
 * create at 2018/7/16 0016  14:59
 * description:  NetworkManager
 */
public class NetworkManager {
    private static ApiService apiService;
    private static SingerService singerService;
    private static volatile NetworkManager instance;
    private Retrofit retrofit;

    public ApiService getApiService() {
        if (apiService == null) {
            apiService = createService(ApiService.class);
        }
        return apiService;
    }

    public SingerService getSongerService() {
        if (singerService == null) {
            singerService = createService(SingerService.class);
        }
        return singerService;
    }

    private NetworkManager() {
        // 构造函数私有化，防止外部实例化
    }

    public static NetworkManager getInstance() {
        if (instance == null) {
            synchronized (NetworkManager.class) {
                if (instance == null) {
                    instance = new NetworkManager();
                }
            }
        }
        return instance;
    }

    /**
     * 创建指定的服务接口实例
     *
     * @param serviceClass 要创建的服务接口类型
     * @param <T>          服务接口的具体类型
     * @return 返回指定类型的服务接口实例
     */
    public <T> T createService(Class<T> serviceClass) {
        if (retrofit == null) {
            synchronized (NetworkManager.class) {
                if (retrofit == null) {
                    retrofit = new Retrofit.Builder()
                            .client(HttpClient.getInstance())
                            .baseUrl(AppConfig.URL)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build();
                }
            }
        }
        return retrofit.create(serviceClass);
    }
}
